﻿using Cysharp.Threading.Tasks;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;


//取消操作 大致原理同Task 中的取消
//通过 CancellationTokenSource 创建对应令牌CancellationToken
//通过token 与 要取消的任务 对应 通过CancellationTokenSource 的Cancel 方法 设置token 标志位 任务取消 token 抛出异常
//捕获异常 任务停止


//async UniTaskVoid 与 async Void 比较
//async Void 是C#提供的  比较重
//async Void最好不要在UniTask 中使用
public class Eight : MonoBehaviour
{
    public GameObject ball;
    public Button btn1;

    public Button btn2;

    public CancellationTokenSource cts;
    // public CancellationToken token;

    private void Start()
    {
        cts = new CancellationTokenSource();
        // token = cts.Token;
        btn1.onClick.AddListener(() =>
        {
            Clik1();
        });
        btn2.onClick.AddListener(() =>
        {
            Click2();
        });
    }

    public async UniTask<int> Move(Transform tf, CancellationToken token)
    {
        float totalTime = 5;
        float currentTime = 0;


        while (currentTime < totalTime)
        {
            currentTime += Time.deltaTime;
            tf.position += new Vector3(1, 0, 0) * Time.deltaTime;

            await UniTask.NextFrame(token); // 等待下一帧,异步取消的关键
        }

        return 0;
    }

    public async void Clik1()
    {
        try
        {
            await Move(ball.transform, cts.Token);
        }
        catch (OperationCanceledException)
        {
            Debug.Log("捕获到异常");
        }
    }

    public async void Click2()
    {
        cts.Cancel();
        cts.Dispose();

        cts = new CancellationTokenSource();
    }
}